package zkdemo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Test;

public class Curator_Lock {
	
	@Test
	public void testLock() throws InterruptedException {
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString("192.168.10.188:2181")
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(3000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.namespace("zk-book")
				.build();
		client.start();
		
		final InterProcessMutex lock = new InterProcessMutex(client, "/lock");
		final CountDownLatch down = new CountDownLatch(1);
		for (int i = 0; i < 10; i++) {
			new Thread(()->{
				try {
					down.await();
					lock.acquire();
				} catch (Exception e) {
					e.printStackTrace();
				}
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
				String orderno = sdf.format(new Date());
				System.out.println("orderno="+orderno);
				try {
					lock.release();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}).start();
		}
		down.countDown();
		Thread.sleep(Long.MAX_VALUE);
	}	
	
	@Test
	public void testNoLock() throws Exception {
		final CountDownLatch down = new CountDownLatch(1);
		for (int i = 0; i < 10; i++) {
			new Thread(()->{
				try {
					down.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
				String orderno = sdf.format(new Date());
				System.out.println("orderno="+orderno);
			}).start();
		}
		down.countDown();
		Thread.sleep(Long.MAX_VALUE);
	}
}
